package com.zerlings.gabeisfaker.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

abstract class BaseFragment<TBinding: ViewDataBinding, TModel: ViewModel>(private val brId: Int, modelClass: Class<TModel>) : Fragment() {

    protected lateinit var binding: TBinding

    protected val viewModel by lazy { ViewModelProvider(this, getViewModelFactory()).get(modelClass) }

    protected val activity by lazy { getActivity() as MainActivity }

    private var viewHolder: View? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (viewHolder == null) {
            binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
            binding.lifecycleOwner = viewLifecycleOwner
            initView(inflater, container, savedInstanceState)
            binding.setVariable(brId, viewModel)
            viewHolder = binding.root
        }
        activity.currentFragment = this
        return binding.root
    }

    protected open fun getViewModelFactory() = defaultViewModelProviderFactory

    protected abstract fun getLayoutId(): Int

    /**
     * 初始化界面元素和成员变量
     * */
    protected abstract fun initView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)

    /**
     * fragment拦截返回键返回true，不拦截返回false
     * */
    abstract fun onBackPressed(): Boolean
}